#include "Input.h"




CInput::~CInput(void)
{
}

CInput::CInput()
{
	this->m_pDirectInput = NULL;
	this->m_pKeyboard = NULL;
}

BOOL CInput::Init(HINSTANCE hInst, HWND hWnd)
{
	HRESULT hResult;
	GetWindowRect(hWnd, &this->m_screenSize);

	hResult = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&this->m_pDirectInput, NULL);
	if (FAILED(hResult))
		return FALSE;

	hResult = this->m_pDirectInput->CreateDevice(GUID_SysKeyboard, &this->m_pKeyboard, NULL);
	if (FAILED(hResult))
		return FALSE;

	hResult = this->m_pKeyboard->SetDataFormat(&c_dfDIKeyboard);
	if (FAILED(hResult))
		return FALSE;

	hResult = this->m_pKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
	if (FAILED(hResult))
		return FALSE;

	hResult = this->m_pKeyboard->Acquire();
	if (FAILED(hResult))
		return FALSE;


	this->ReadKeyboard();
	for (int i = 0; i < 256; i++)
		this->m_oldkeyboardState[i] = this->m_keyboardState[i];	

	return TRUE;
}

BOOL CInput::ReadKeyboard()
{
	HRESULT hResult;

	// Clean keyboard buf
	ZeroMemory( this->m_keyboardState, sizeof(this->m_keyboardState) );

	this->m_pKeyboard->Poll();
	hResult = this->m_pKeyboard->GetDeviceState(sizeof(this->m_keyboardState), (LPVOID)&this->m_keyboardState);
	if (FAILED(hResult))
	{
		this->m_pKeyboard->Acquire();
	}

	return TRUE;
}


void CInput::Update()
{
	for (int i = 0; i < 256; i++)
		this->m_oldkeyboardState[i] = this->m_keyboardState[i];
	this->ReadKeyboard();

}


BOOL CInput::KeyDown(unsigned char key)
{
	return this->m_keyboardState[key] & 0x80;
}

BOOL CInput::KeyUp(unsigned char key)
{
	return !(this->m_keyboardState[key] & 0x80);
}

BOOL CInput::KeyPressed(unsigned char key)
{
	return (this->m_keyboardState[key] & 0x80) && !(this->m_oldkeyboardState[key] && 0x80);
}

BOOL CInput::KeyReleased(unsigned char key)
{
	return (this->m_oldkeyboardState[key] & 0x80) && !(this->m_keyboardState[key] & 0x80);
}

